package com.usian.controller;

import com.usian.User;
import com.usian.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    UserFeign userFeign;

    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    public User getUserBy(@PathVariable Integer id){
        ServiceInstance instance = loadBalancerClient.choose("ribbon-provider");
        //指定要调用的服务
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/findById/"+id;
        return restTemplate.getForObject(url, User.class);
    }

    @RequestMapping(value="/feign/{id}",method= RequestMethod.GET)
    public User getUserByFeign(@PathVariable Integer id){
        User user = userFeign.findUserById(id);
        return user;
    }

}
